/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { useState, useCallback, useRef } from 'react';
/**
 * @param {number} delay 轮询间隔
 * @param {number} maxTimer 最大轮询时间（分钟）
 * @param {Function} request 请求函数
 *  */
const useLoopRequest = ({ delay = 1000, maxTimer = 1, request = () => {} }) => {
  const [overdue, setOverdue] = useState(false);
  const [pause, setPause] = useState(true)
  const timer = useRef(null);

  const stopLoop = useCallback(() => {
    if (timer.current) {
      setOverdue(false);
      setPause(true)
      clearInterval(timer.current);
      timer.current = null;
    }
  }, []);

  const startLoop = useCallback(() => {
    let limitTimer = 0;
    const max_timer = maxTimer * 60 * 1000; // 分钟
    stopLoop();
    timer.current = setInterval(() => {
      limitTimer += delay;
      if (limitTimer >= max_timer) {
        // 提示过期
        setOverdue(true);
        stopLoop();
        return;
      }
      setPause(false)
      request();
    }, delay);
  }, [maxTimer, timer, delay, request, stopLoop]);

  return {
    startLoop,
    stopLoop,
    overdue,
    pause,
  };
};

export default useLoopRequest;
